// 生成19位唯一数字标识符
export const randomNumber = () => {
  var timestamp = Date.now().toString(); // 获取当前时间戳
  var random = Math.floor(Math.random() * 9000000000000000) + 1000000000000000; // 生成15位随机数
  var identifier = timestamp + random.toString(); // 结合时间戳和随机数
  if (identifier.length > 19) {
    identifier = identifier.substr(0, 19); // 如果标识符超过19位，则截取前19位
  }
  if (identifier.charAt(0) === "0") {
    identifier = "1" + identifier.substr(1); // 如果开头是0，则将第一个字符替换为1
  }
  return identifier;
};

/**
 * 生成唯一ID
 */
export function guuid() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

function copyTextToClipboardFallback(text) {
  const textArea = document.createElement("textarea");
  textArea.value = text;

  // 避免文本域在页面上可见
  textArea.style.top = "0";
  textArea.style.left = "0";
  textArea.style.position = "fixed";

  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();

  try {
    const successful = document.execCommand("copy");
    const msg = successful ? "successful" : "unsuccessful";
    console.log("Text copy command was " + msg);
  } catch (err) {
    console.error("无法复制文本：", err);
  }

  // 移除文本域
  document.body.removeChild(textArea);
}

export async function copyTextToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text);
  } catch (err) {
    copyTextToClipboardFallback(text);
  }
}

export function parseSearchToObject(search: string): Record<string, string> {
  // 如果没有查询字符串，直接返回一个空对象
  if (!search) {
    return {};
  }

  // 去掉开头的 '?'
  if (search.startsWith("?")) {
    search = search.slice(1);
  }

  // 使用 URLSearchParams 对象来解析查询字符串
  const params = new URLSearchParams(search);
  const result = {};

  // 遍历所有的参数，并添加到结果对象中
  for (const [key, value] of params.entries()) {
    result[key] = value;
  }

  return result;
}
